<template>
  <div class="student-container">
    <!-- 查询区域 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="searchForm" ref="searchForm" label-width="80px" class="search-form">
        <el-form-item label="ID" prop="id">
          <el-input v-model="searchForm.id" placeholder="请输入学生ID" clearable></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="searchForm.name" placeholder="请输入学生姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="searchForm.sex" placeholder="请选择性别" clearable>
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 添加按钮 -->
    <div class="add-button-container">
      <el-button type="primary" @click="showAddDialog = true">
        <i class="el-icon-plus"></i> 添加学生
      </el-button>
    </div>

    <!-- 学生表格 -->
    <el-table
        :data="tableData"
        style="width: 100%"
        border
        stripe>
      <el-table-column
          prop="id"
          label="ID"
          width="180">
      </el-table-column>
      <el-table-column
          prop="name"
          label="姓名"
          width="180">
      </el-table-column>
      <el-table-column
          prop="sex"
          label="性别">
        <template #default="scope">
          <el-tag :type="scope.row.sex === '男' ? 'primary' : 'success'">
            {{ scope.row.sex }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
          prop="phone"
          label="电话"
          width="180">
      </el-table-column>
      <el-table-column
          prop="money"
          label="金额"
          width="180">
        <template #default="scope">
          {{ scope.row.money | formatMoney }}
        </template>
      </el-table-column>
      <el-table-column
          label="操作"
          width="260">
        <template #default="scope">
          <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加学生弹窗 -->
    <el-dialog
        title="添加学生"
        :visible.sync="showAddDialog"
        width="500px"
        :close-on-click-modal="false">
      <el-form :model="studentForm" :rules="rules" ref="studentForm" label-width="80px" class="add-form">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="studentForm.name" placeholder="请输入学生姓名"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="studentForm.phone" placeholder="请输入电话号码"></el-input>
        </el-form-item>
        <el-form-item label="金额" prop="money">
          <el-input
              v-model.number="studentForm.money"
              type="number"
              placeholder="请输入金额"
              min="0"
              step="0.01">
          </el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="studentForm.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑学生弹窗 -->
    <el-dialog
        title="编辑学生"
        :visible.sync="showEditDialog"
        width="500px"
        :close-on-click-modal="false">
      <el-form :model="editForm" :rules="rules" ref="editForm" label-width="80px" class="edit-form">
        <el-form-item label="ID" prop="id">
          <el-input v-model="editForm.id" disabled placeholder="学生ID"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入学生姓名"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入电话号码"></el-input>
        </el-form-item>
        <el-form-item label="金额" prop="money">
          <el-input
              v-model.number="editForm.money"
              type="number"
              placeholder="请输入金额"
              min="0"
              step="0.01">
          </el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="editForm.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getStudents, addStudent, deleteStudent, searchStudents, updateStudent } from "../../Api/User";

export default {
  name: "students",
  filters: {
    formatMoney(value) {
      if (value === undefined || value === null) return '0.00';
      return parseFloat(value).toFixed(2);
    }
  },
  data() {
    return {
      tableData: [],
      showAddDialog: false,
      showEditDialog: false,
      // 查询表单数据
      searchForm: {
        id: '',
        name: '',
        sex: ''
      },
      // 添加学生表单数据
      studentForm: {
        name: '',
        phone: '',
        money: null,
        sex: '男'
      },
      // 编辑学生表单数据
      editForm: {
        id: '',
        name: '',
        phone: '',
        money: null,
        sex: '男'
      },
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '请输入学生姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码格式', trigger: 'blur' }
        ],
        money: [
          { required: true, message: '请输入金额', trigger: 'blur' },
          { type: 'number', min: 0, message: '金额必须大于等于0', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    // 处理后端数据，映射正确字段并转换性别
    processStudentData(rawData) {
      if (!Array.isArray(rawData)) {
        console.warn("后端返回的数据不是数组格式");
        return [];
      }

      return rawData.map(item => ({
        id: item.id || '',
        name: item.username || '',
        sex: this.convertSex(item.sex),
        phone: item.phone || '',
        money: item.money !== undefined ? Number(item.money) : 0
      }));
    },

    // 转换性别编码：0→女，1→男，其他→未知
    convertSex(sexCode) {
      switch(sexCode) {
        case 0:
          return '女';
        case 1:
          return '男';
        default:
          return '未知';
      }
    },

    // 提交添加学生表单
    submitForm() {
      this.$refs.studentForm.validate((valid) => {
        if (valid) {
          // 转换性别为数字编码
          const sexCode = this.studentForm.sex === '男' ? 1 : 0;

          // 构建完整的提交数据对象
          const submitData = {
            username: this.studentForm.name,
            phone: this.studentForm.phone,  // 确保phone字段正确传递
            money: Number(this.studentForm.money),  // 确保money为数字类型
            sex: sexCode
          };

          // 调试：打印提交的数据，确认phone和money是否存在
          console.log("添加学生提交数据:", submitData);

          // 发送请求前再次确认数据完整性
          if (!submitData.phone) {
            this.$message.error('电话号码不能为空');
            return;
          }
          if (submitData.money === null || submitData.money === undefined) {
            this.$message.error('金额不能为空');
            return;
          }

          addStudent(submitData).then(res => {
            console.log("添加接口响应:", res);
            if (res && res.code === "200") {
              this.$message.success('添加成功');
              this.showAddDialog = false;
              this.resetForm();
              this.fetchStudentList();
            } else {
              this.$message.error(res?.msg || '添加失败');
            }
          }).catch(error => {
            console.error("添加学生失败：", error);
            this.$message.error('添加失败，请稍后重试');
          });
        } else {
          // 表单验证失败时提示
          this.$message.warning('请完善表单信息');
          return false;
        }
      });
    },

    // 提交编辑学生表单
    submitEditForm() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          const sexCode = this.editForm.sex === '男' ? 1 : 0;

          const submitData = {
            id: this.editForm.id,
            username: this.editForm.name,
            phone: this.editForm.phone,  // 确保phone字段正确传递
            money: Number(this.editForm.money),  // 确保money为数字类型
            sex: sexCode
          };

          // 调试：打印编辑提交的数据
          console.log("编辑学生提交数据:", submitData);

          updateStudent(submitData).then(res => {
            console.log("编辑接口响应:", res);
            if (res && res.code === "200") {
              this.$message.success('修改成功');
              this.showEditDialog = false;
              this.fetchStudentList();
            } else {
              this.$message.error(res?.msg || '修改失败');
            }
          }).catch(error => {
            console.error("修改学生失败：", error);
            this.$message.error('修改失败，请稍后重试');
          });
        } else {
          this.$message.warning('请完善表单信息');
          return false;
        }
      });
    },

    // 处理编辑操作
    handleEdit(row) {
      // 填充编辑表单数据，确保所有字段都被正确赋值
      this.editForm = {
        id: row.id,
        name: row.name,
        phone: row.phone,
        money: Number(row.money),
        sex: row.sex
      };
      console.log("编辑表单初始化数据:", this.editForm);
      this.showEditDialog = true;
    },

    // 重置添加表单
    resetForm() {
      this.$refs.studentForm.resetFields();
      // 显式重置表单字段
      this.studentForm = {
        name: '',
        phone: '',
        money: null,
        sex: '男'
      };
    },

    // 重置查询表单
    resetSearch() {
      this.$refs.searchForm.resetFields();
      this.fetchStudentList();
    },

    // 处理查询
    handleSearch() {
      let sexCode = null;
      if (this.searchForm.sex) {
        sexCode = this.searchForm.sex === '男' ? 1 : 0;
      }

      const searchData = {
        id: this.searchForm.id || null,
        username: this.searchForm.name || null,
        sex: sexCode
      };

      searchStudents(searchData).then(res => {
        if (res && res.code === "200") {
          this.tableData = this.processStudentData(res.data);
        } else {
          this.$message.error(res?.msg || '查询失败');
        }
      }).catch(error => {
        console.error("查询学生失败：", error);
        this.$message.error('查询失败，请稍后重试');
      });
    },

    // 删除学生
    handleDelete(id) {
      this.$confirm('确定要删除这条记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const deleteData = { id: id };

        deleteStudent(deleteData).then(res => {
          if (res && res.code === "200") {
            this.$message.success('删除成功');
            this.fetchStudentList();
          } else {
            this.$message.error(res?.msg || '删除失败');
          }
        }).catch(error => {
          console.error("删除学生失败：", error);
          this.$message.error('删除失败，请稍后重试');
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    // 获取学生列表
    fetchStudentList() {
      getStudents().then(res => {
        console.log("获取学生列表响应:", res);
        if (res && res.code === "200") {
          this.tableData = this.processStudentData(res.data);
        } else {
          console.log("后端返回业务错误：", res?.msg || "未知错误");
        }
      }).catch(error => {
        console.error("请求学生数据失败：", error);
      });
    }
  },
  created() {
    this.fetchStudentList();
  }
}
</script>

<style scoped>
.student-container {
  padding: 20px;
}

.search-card, .add-form-card {
  margin-bottom: 20px;
  border-radius: 20px;
}

.search-form, .add-form, .edit-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: flex-end;
}

.add-button-container {
  margin-bottom: 20px;
  text-align: right;
}

::v-deep .el-table {
  margin-top: 10px;
  border-radius: 20px;
}

::v-deep .el-dialog__body {
  padding: 20px;
}

::v-deep .el-button--small + .el-button--small {
  margin-left: 10px;
}

/* 高亮显示phone和money输入框，方便检查 */
::v-deep .el-form-item__content input[placeholder*="电话"],
::v-deep .el-form-item__content input[placeholder*="金额"] {
  border-left: 3px solid #409EFF;
}
</style>
